package com.wxtt.android.adapter;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import java.util.ArrayList;

/**
 * 说明：首页ViewPageAdapter
 * <p/>
 * 作者：fanly
 * <p/>
 * 时间：2016/1/2 23:42
 * <p/>
 * 版本：verson 1.0
 */
public class ViewPageFragmentAdapter extends FragmentStatePagerAdapter {

    private Context mContext;
    private ViewPager mViewPager;
    private TabLayout mTab;
    private ArrayList<ViewPageInfo> mPageInfos = new ArrayList<>();

    public ViewPageFragmentAdapter(FragmentManager fm,ViewPager pager,TabLayout tab) {
        super(fm);
        mViewPager = pager;
        mTab = tab;
        mContext = mViewPager.getContext();
        mViewPager.setAdapter(this);
        mViewPager.setOffscreenPageLimit(3);
        initTabLayout(tab);
    }

    private void initTabLayout(TabLayout tab) {
        //Tab数量比较少使用
        tab.setTabMode(TabLayout.MODE_FIXED);
    }

    @Override
    public Fragment getItem(int position) {
        ViewPageInfo info = mPageInfos.get(position);
        return Fragment.instantiate(mContext,info.clazz.getName(),info.params);
    }

    @Override
    public int getItemPosition(Object object) {
        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mPageInfos.get(position%mPageInfos.size()).title;
    }

    @Override
    public int getCount() {
        return mPageInfos.size();
    }

    /**
     * 说明：添加一个标签
     * @param title
     * @param clazz
     * @param params
     */
    public void addTab(String title,Class<?> clazz,Bundle params){
        ViewPageInfo info = new ViewPageInfo(title,clazz,params);
        addFragment(info);
        mTab.setupWithViewPager(mViewPager);
    }

    private void addFragment(ViewPageInfo info){
        if (info == null) return;
        mPageInfos.add(info);
        notifyDataSetChanged();
    }

    /**
     * 说明：移除一个标签
     * @param index
     */
    public void removeTab(int index){
        if (mPageInfos.isEmpty())return;
        if (index < 0) index = 0;
        if (index >= mPageInfos.size()) index = mPageInfos.size() - 1;
        mPageInfos.remove(index);
        notifyDataSetChanged();
    }
}
